<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

class ManyiController extends PayController{
    protected $config;
    protected $key;
    protected $url;

    public function pay($array){
        $this->config = M("Channel")->where(array('id'=>$array['channel']))->find();
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'005']);
        }
		
        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();

        if($return['amount']>=1000){
            $data['trxType'] = 'UNIONPAY_QRCODE_LARGE';
        }else{
            $data['trxType'] = 'UNIONPAY_QRCODE';
        }
        $data['merchantNo'] = $this->config['mch_id'];
        $data['orderNum'] = $return['orderid'];
        $data['amount'] = number_format($return['amount'],2,'.','');
        $data['goodsName'] = 'pay';
        $data['timeOut'] = date("YmdHis",time()+3600);
        $data['callbackUrl'] = $return['callbackurl'];
        $data['serverCallbackUrl'] = $return['notifyurl'];
        $data['orderIp'] = $_SERVER['REMOTE_ADDR'];
        $data['encrypt'] = 'T0';

        $str = '';
        foreach($data as $k=>$v){
            $str .= "#".$v;
        }
        $str .= "#".$this->config['signkey'];
        $data['sign'] = md5($str);

        function curl($apiurl,$data){
            $con = curl_init($apiurl);
            curl_setopt($con, CURLOPT_HEADER, false);
            curl_setopt($con, CURLOPT_POSTFIELDS, arrToUrlStr($data));
            curl_setopt($con, CURLOPT_POST, true);
            curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($con, CURLOPT_TIMEOUT, 10);
            $res = curl_exec($con);
            curl_close($con);

            return $res;
        }

        $res = trim(curl($this->config['gateway'], $data));


        if(!$res){
            $this->showmessage('请求失败!',['code'=>'005']);
        }

        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res]);

        $res = json_decode($res, true);
        if($res['retCode'] != '1000'){
            $this->showmessage($res['retMsg'],['code'=>'005']);
        }

        $code = $res['qrCode'];

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".$code);
        $this->display("WeiXin/Pay");
    }

    //通知
    public function notifyurl(){

        /*$_POST = array (
            'r5_business' => 'UnionPay',
            'trxType' => 'UNIONPAY_QRCODE',
            'r6_timestamp' => '2018-06-13 20:32:43',
            'r4_bankId' => 'UnionPay',
            'r8_orderStatus' => 'SUCCESS',
            'sign' => 'fd491cfa15331a8962f94dce1dca794a',
            'r1_merchantNo' => 'B100004142',
            'r9_serialNumber' => 'LS180613203243JL7',
            'r3_amount' => '50.00',
            'retCode' => '0000',
            'r7_completeDate' => '2018-06-13 20:33:42',
            'r2_orderNumber' => '201806132032433039599',
            'r10_t0PayResult' => '1',
        );*/

        $p = $_POST;
        if(!$p || empty($p)){
            exit;
        }

        //组装签名串数组
        $sign = $p['sign'];
        unset($p['sign']);
        if(isset($p['retMsg'])){
            unset($p['retMsg']);
        }
        $trxType = $p['trxType'];
        $retCode = $p['retCode'];
        $r10_t0PayResult = $p['r10_t0PayResult'];
        unset($p['trxType']);
        unset($p['retCode']);
        unset($p['r10_t0PayResult']);
        ksort($p);
        $d = array("trxType"=>$trxType, "retCode"=>$retCode);
        $p = array_merge($d,$p, array("r10_t0PayResult"=>$r10_t0PayResult));

        //获取订单信息
        $orderid = $p['r2_orderNumber'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        $s = file_get_contents('php://input');
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array("server_return"=> $s,"pay_orderid_rd"=>$p['r9_serialNumber']));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Manyi'))->find();

        //验签
        $str = '';
        //ksort($p);
        foreach($p as $k=>$v){
            $str .= "#".$v;
        }
        $str .= "#".$this->config['signkey'];
        $sign2 = md5($str);
        if($sign != $sign2){
            exit("sign_wrong");
        }
        if($p['retCode'] != '0000'){
            exit("pail_fail");
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Manyi",0);

        //回调成功
        echo 'SUCCESS'; exit;
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }

    public function send()
    {
        $return=array(
            'memberid'=>$this->data['pay_memberid'],
            'orderid'=>$this->data['pay_orderid'],
            'amount'=>$this->data['pay_actualamount'],
            'returncode'=>'00',
            'attach'=>$this->data['pay_attach'],
        );

        $sHtml='<form action="'.$this->data['pay_callbackurl'].'" method="post" id="sendForm" name="sendForm">';

        foreach($return as $filed=>$code)
        {
            $sHtml.="<input type='hidden' name='".$filed."' value='".$code."' />";
        }

        $sHtml.="</form>";

        $sHtml.="<script>document.forms['sendForm'].submit();</script>";

        echo $sHtml;
    }




    public function prepareSign($data) {
        //1网银支付
        if($data['service'] == 'TRADE.B2C') {
            $result = sprintf(
                "service=%s&version=%s&merId=%s&tradeNo=%s&tradeDate=%s&amount=%s&notifyUrl=%s&extra=%s&summary=%s&expireTime=%s&clientIp=%s&bankId=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount'],
                $data['notifyUrl'],
                $data['extra'],
                $data['summary'],
                $data['expireTime'],
                $data['clientIp'],
                $data['bankId']
            );


            return $result;
            //2扫码支付
        }else if($data['service'] == 'TRADE.SCANPAY'){
            $result = sprintf(
                "service=%s&version=%s&merId=%s&typeId=%s&tradeNo=%s&tradeDate=%s&amount=%s&notifyUrl=%s&extra=%s&summary=%s&expireTime=%s&clientIp=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['typeId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount'],
                $data['notifyUrl'],
                $data['extra'],
                $data['summary'],
                $data['expireTime'],
                $data['clientIp']


            );

            return $result;

            //3支付订单查询
        }else if($data['service'] == 'TRADE.QUERY'){
            $result = sprintf(
                "service=%s&version=%s&merId=%s&tradeNo=%s&tradeDate=%s&amount=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount']
            );

            return $result;
            //4退款申请
        }else if($data['service'] == 'TRADE.REFUND'){
            $result = sprintf(
                "service=%s&version=%s&merId=%s&tradeNo=%s&tradeDate=%s&amount=%s&summary=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount'],
                $data['summary']
            );
            return $result;
            //5单笔委托结算
        }else if($data['service'] == 'TRADE.SETTLE'){

            $result = sprintf(
                "service=%s&version=%s&merId=%s&tradeNo=%s&tradeDate=%s&amount=%s&notifyUrl=%s&extra=%s&summary=%s&bankCardNo=%s&bankCardName=%s&bankId=%s&bankName=%s&purpose=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount'],
                $data['notifyUrl'],
                $data['extra'],
                $data['summary'],
                $data['bankCardNo'],
                $data['bankCardName'],
                $data['bankId'],
                $data['bankName'],
                $data['purpose']

            );

            return $result;

            //6单笔委托结算查询
        }else if($data['service'] == 'TRADE.SETTLE.QUERY'){
            $result = sprintf(
                "service=%s&version=%s&merId=%s&tradeNo=%s&tradeDate=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate']
            );
            return $result;
            //7回调
        }else if($data['service'] == 'TRADE.NOTIFY'){
            $result = sprintf(
                "service=%s&merId=%s&tradeNo=%s&tradeDate=%s&opeNo=%s&opeDate=%s&amount=%s&status=%s&extra=%s&payTime=%s",
                $data['service'],
                $data['merId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['opeNo'],
                $data['opeDate'],
                $data['amount'],
                $data['status'],
                $data['extra'],
                $data['payTime']
            );
            return $result;
            //h5支付
        }else if($data['service'] == 'TRADE.H5PAY'){
            $result = sprintf(
                "service=%s&version=%s&merId=%s&typeId=%s&tradeNo=%s&tradeDate=%s&amount=%s&notifyUrl=%s&extra=%s&summary=%s&expireTime=%s&clientIp=%s",
                $data['service'],
                $data['version'],
                $data['merId'],
                $data['typeId'],
                $data['tradeNo'],
                $data['tradeDate'],
                $data['amount'],
                $data['notifyUrl'],
                $data['extra'],
                $data['summary'],
                $data['expireTime'],
                $data['clientIp']


            );
            return $result;
        }
    }

    public function sign($data) {
        $signature=md5($data.$this->Key);
        return $signature;
    }

    /**
     * 创建表单
     * @data		表单内容
     * @gateway 支付网关地址
     */
    function buildForms($data, $gateway) {
        $sHtml = "<form id='paysubmit' name='bankPaySubmit' action='".$gateway."' method='post'>";
        while (list ($key, $val) = each ($data)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }
        $sHtml.= "</form>";
        $sHtml.= "<script>document.forms['bankPaySubmit'].submit();</script>";

        return $sHtml;
    }
}